﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace testTPLInWinForm
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            label2.Text = "";
            label1.Text = "Milliseconds: ";
            var watch = Stopwatch.StartNew();

            List<Task> tasks = new List<Task>();

            var uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
            for (int i = 2; i < 20; i++)
            {
                int j = i;
                var compute = Task.Factory.StartNew(() =>
                {
                    return SumRootN(j);
                });

                tasks.Add(compute);

                // Continue with other actions after the task finished.
                var display = compute.ContinueWith(resultTask =>
                    {
                        label2.Text += "root " + j.ToString() + " " + resultTask.Result.ToString() + Environment.NewLine;
                    }, uiTaskScheduler);
            }
            
            // Waits for an array of tasks to finish, then perform the UI task.
            Task.Factory.ContinueWhenAll(tasks.ToArray(), 
                r =>
                {
                    var time = watch.ElapsedMilliseconds;
                    label1.Text = time.ToString();
                }, CancellationToken.None, TaskContinuationOptions.None, uiTaskScheduler);
        }

        private double SumRootN(int root)
        {
            double result = 0;
            for (int i = 1; i < 10000000; i++)
            {
                result += Math.Exp(Math.Log(i) / root);
            }

            return result;
        }
    }
}
